use std::error::{self};
use std::process::{Command, Stdio};
use std::io::{BufRead, BufReader};

use dirs;

fn main() {
    
    let path = std::env::current_exe().unwrap().parent().unwrap().display().to_string();
    println!("当前目录路径: {}", path);
    
    exec_cmd("chmod +x gradlew").expect("修改失败");
    exec_cmd("./gradlew app:assembleRelease").expect("打包 apk 失败");

    // 获取桌面路径
    let mut desktop_dir = String::new();
    if let Some(desktop_path) = dirs::desktop_dir() {
        desktop_dir = format!("{}/apk", desktop_path.display()).to_string();
        println!("桌面路径: {}", desktop_path.display());
    } else {
        println!("无法获取桌面路径");
    }
    let cmd = format!("mv {}/app/build/outputs/apk/release/*.apk {}", path, desktop_dir);
    exec_cmd(cmd.as_str()).expect("移动失败");
}

fn exec_cmd(cmd_str: &str) -> Result<(), Box<dyn error::Error>> {
    // 1. 执行 gradle assembleRelease 命令
    let mut cmd = Command::new("sh")
        .arg("-c")
        .arg(cmd_str)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect(&format!("命令执行失败 {}", cmd_str));

    // 2. 实时显示输出进度
    if let Some(stdout) = cmd.stdout.take() {
        let reader = BufReader::new(stdout);
        for line in reader.lines() {
            if let Ok(l) = line {
                println!("{}", l);
            }
        }
    }
    let status = cmd.wait().expect("命令执行失败");
    if status.success() {
        println!("命令执行成功{}", cmd_str);
        Ok(())
    } else {
        println!("命令执行失败 {}", cmd_str);
        Err((format!("命令执行失败 {}", cmd_str)).into())
    }
}
